//
//  AlarmViewController.m
//  project
//
//  Created by 圆圆陈 on 2017/12/16.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "AlarmViewController.h"
#import "EditAlarmViewController.h"
@interface AlarmViewController ()<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, assign) BOOL        selected;
@end

@implementation AlarmViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [_tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *StateView = [[UIView alloc] init];
    StateView.frame           = CGRectMake(0, 0, kSCREEN_WIDTH, 20);
    StateView.backgroundColor = BBIGSTATECOLOR;
    [self.view addSubview:StateView];
    
    UIView *naView = [[UIView alloc] init];
    naView.frame           = CGRectMake(0, 20+FitSimpleIpx(0, 20), kSCREEN_WIDTH, 44);
    naView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:naView];
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20), screenWidth, 44)];
    lable.textColor     = [UIColor blackColor];
    lable.font          = SNFONT(17);
    lable.textAlignment = NSTextAlignmentCenter;
    lable.text          = HHH_Text(@"闹钟");
    
    [self.view addSubview:lable];
    
    UIButton *leftButton = [[UIButton alloc] init];
    leftButton.frame = CGRectMake(5, 20+FitSimpleIpx(0, 20), 44, 44);
    [leftButton setImageNormal:@"进入"];
    [leftButton addTarget:self action:@selector(leftbuttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    
    UIButton *rightButton = [[UIButton alloc] init];
    rightButton.frame = CGRectMake(HHHWIDTH-44, 20+FitSimpleIpx(0, 20), 44, 44);
    [rightButton setImageNormal:@"添加加号无边框"];
    [rightButton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightButton];
    
    _tableView                 = [[UITableView alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20)+44+2, HHHWIDTH, HHHHEIGHT-20-FitSimpleIpx(0, 20)-44-2) style:UITableViewStylePlain];
    _tableView.delegate        = self;
    _tableView.dataSource      = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    UIView *uiview = [[UIView alloc] init];
    uiview.frame = SNFRAME(0, 0, HHHWIDTH, 56);
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 6, HHHWIDTH -10, 44)];
    label.textColor = SNCOLORBLACK;
    label.text      = SN_Text(@"最多可以设置5个闹钟");
    label.font = SNFONT(16);
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    [uiview addSubview:label];
    
    _tableView.tableFooterView = uiview;
    
    UIImageView *shadowLine = [[UIImageView alloc] init];
    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44 -2, HHHWIDTH, 2);
    shadowLine.image = [UIImage image:@"lineImage"];
    [self.view addSubview:shadowLine];
}

- (void)leftbuttonClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonClick:(UIButton *)sender {
    if (SN_USER.showAlarmArray.count == 5) {
        SHOWMBProgressHUD(nil, HHH_Text(@"最多可以设置5个闹钟"), nil, NO, 1);
        return;
    }
    sender.enabled = NO;
    EditAlarmViewController *editVC = [EditAlarmViewController new];
    editVC.type  = 0;
    editVC.model = [[SNAlarmModel alloc]init];
    [self.navigationController pushViewController:editVC animated:YES];
    sender.enabled = YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return SN_USER.showAlarmArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return FitH(80);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (!cell) {
        cell                = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    SNAlarmModel *model = SN_USER.showAlarmArray[indexPath.row];
    
    cell.textLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", model.hours, model.mins];
    cell.textLabel.font = [UIFont systemFontOfSize:FitFont(18)];
    NSArray  *arr = @[HHH_Text(@"周一,"), HHH_Text(@"周二,"), HHH_Text(@"周三,"), HHH_Text(@"周四,"), HHH_Text(@"周五,"), HHH_Text(@"周六,"), HHH_Text(@"周日,")];
    NSString *str = [NSString stringWithFormat:@"%@%@%@%@%@%@%@", model.MON ? arr[0] : @"", model.TUE ? arr[1] : @"", model.WED ? arr[2] : @"", model.THU ? arr[3] : @"", model.FRI ? arr[4] : @"", model.SAT ? arr[5] : @"", model.SUN ? arr[6] : @""];
    if (str.length > 0) {
        cell.detailTextLabel.text = [str substringToIndex:str.length-1];
    } else {
        NSDate *date = [NSDate date];
        if ([date compareWithDate:model.date]) {
            cell.detailTextLabel.text = SN_Text(@"今天");
            if ([date compare:model.date] == 1 && model.open) {
                model.open = NO;
                [SN_USER.showAlarmArray replaceObjectAtIndex:model.orderIndex withObject:model];
                for (int i = 0; i < SN_USER.showAlarmArray.count; i++) {
                    [SN_USER.alarmArray replaceObjectAtIndex:i withObject:SN_USER.showAlarmArray[i]];
                }
                [SN_USER updateToDB];
            }
        } else {
            if ([[NSDate dateByString:date.dateToDayString] dateByDistanceDaysWithDate:[NSDate dateByString:model.date.dateToDayString]] == 1) {
                cell.detailTextLabel.text = SN_Text(@"明天");
            }
            else if ([[NSDate dateByString:date.dateToDayString] dateByDistanceDaysWithDate:[NSDate dateByString:model.date.dateToDayString]]<0){
                model.open = NO;
                [SN_USER.showAlarmArray replaceObjectAtIndex:model.orderIndex withObject:model];
                for (int i = 0; i < SN_USER.showAlarmArray.count; i++) {
                    [SN_USER.alarmArray replaceObjectAtIndex:i withObject:SN_USER.showAlarmArray[i]];
                }
                [SN_USER updateToDB];
                 cell.detailTextLabel.text = model.date.dateToDayString;
            }
            else {
                cell.detailTextLabel.text = model.date.dateToDayString;
            }
        }
    }
    
    ZJSwitch *btn = [[ZJSwitch alloc] initWithFrame:CGRectMake(HHHWIDTH-50, FitH(10), 50, 22)];
    btn.tag = 100 +indexPath.row;
    btn.on = model.open;
    [btn addTarget:self action:@selector(handleSwitchEvent:) forControlEvents:UIControlEventValueChanged];
    cell.accessoryView = btn;
    
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, FitH(80)-1, HHHWIDTH, 1)];
    line.backgroundColor = SNCOLORSEPRATE;
    [cell addSubview:line];
    
    return cell;
}

- (void)handleSwitchEvent:(ZJSwitch *)sender {
    SNAlarmModel *model = SN_USER.showAlarmArray[sender.tag-100];
    if (sender.on) {
        model.open = YES;
        if (model.Once && [model.date compare:[NSDate date]]==-1) {
            NSInteger dayCount = [[NSDate dateByString:model.date.dateToDayString] dateByDistanceDaysWithDate:[NSDate dateByString:[NSDate date].dateToDayString]];
            model.date = [model.date dateByAddingDays:dayCount==0?1:dayCount];
        }
        [_tableView reloadData];
    } else {
        model.open = NO;
    }
    [SN_USER.showAlarmArray replaceObjectAtIndex:sender.tag-100 withObject:model];
    for (int i = 0; i < SN_USER.showAlarmArray.count; i++) {
        [SN_USER.alarmArray replaceObjectAtIndex:i withObject:SN_USER.showAlarmArray[i]];
    }
    [SN_USER updateToDB];
    [SN_EveryDayModelHelp startSetAlarmClock];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.selected == NO) {
        self.selected = YES;
        EditAlarmViewController *editVC = [EditAlarmViewController new];
        editVC.type  = 1;
        editVC.model = SN_USER.showAlarmArray[indexPath.row];
        [self.navigationController pushViewController:editVC animated:YES];
        self.selected = NO;
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:HHH_Text(@"删除")  handler:^(UITableViewRowAction *_Nonnull action, NSIndexPath *_Nonnull indexPath) {
        //删除当前的model
        [SN_USER.showAlarmArray removeObjectAtIndex:indexPath.row];
        //将数组中剩余model的orderIndex重置
        for (int i = 0; i < SN_USER.showAlarmArray.count; i++) {
            SNAlarmModel *showModel = SN_USER.showAlarmArray[i];
            showModel.orderIndex = i;
            [SN_USER.showAlarmArray replaceObjectAtIndex:i withObject:showModel];
        }
        //往数组中添加初始化的model 便于覆盖calendarArray中的model
        SNAlarmModel *model = [[SNAlarmModel alloc]init];
        model.orderIndex = SN_USER.showAlarmArray.count;
        [SN_USER.showAlarmArray addObject:model];
        //覆盖
        for (int i = 0; i < SN_USER.showAlarmArray.count; i++) {
            [SN_USER.alarmArray replaceObjectAtIndex:i withObject:SN_USER.showAlarmArray[i]];
        }
        [SN_EveryDayModelHelp startSetAlarmClock];
        //删除之前填充的初始化的model,方便增加新的闹钟
        [SN_USER.showAlarmArray removeLastObject];
        [SN_USER updateToDB];
        [tableView reloadData];
    }];
    
    rowAction.backgroundColor = SNCOLORBLACK;
    return @[rowAction];
}

- (nullable UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(tvos){
    // delete action
    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:HHH_Text(@"删除")
                                                                             handler:^(UIContextualAction *_Nonnull action, __kindof UIView *_Nonnull sourceView,
                                                                                       void (^_Nonnull completionHandler)(BOOL)){
                                                                                 [tableView setEditing:NO animated:YES]; // 这句很重要，退出编辑模式，隐藏左滑菜单
                                                                                 //删除当前的model
                                                                                 [SN_USER.showAlarmArray removeObjectAtIndex:indexPath.row];
                                                                                 //将数组中剩余model的orderIndex重置
                                                                                 for (int i = 0; i < SN_USER.showAlarmArray.count; i++) {
                                                                                     SNAlarmModel *showModel = SN_USER.showAlarmArray[i];
                                                                                     showModel.orderIndex = i;
                                                                                     [SN_USER.showAlarmArray replaceObjectAtIndex:i withObject:showModel];
                                                                                 }
                                                                                 //往数组中添加初始化的model 便于覆盖calendarArray中的model
                                                                                 SNAlarmModel *model = [[SNAlarmModel alloc]init];
                                                                                 model.orderIndex = SN_USER.showAlarmArray.count;
                                                                                 [SN_USER.showAlarmArray addObject:model];
                                                                                 //覆盖
                                                                                 for (int i = 0; i < SN_USER.showAlarmArray.count; i++) {
                                                                                     [SN_USER.alarmArray replaceObjectAtIndex:i withObject:SN_USER.showAlarmArray[i]];
                                                                                 }
                                                                                 [SN_EveryDayModelHelp startSetAlarmClock];
                                                                                 //删除之前填充的初始化的model,方便增加新的闹钟
                                                                                 [SN_USER.showAlarmArray removeLastObject];
                                                                                 [SN_USER updateToDB];
                                                                                 [tableView reloadData];
                                                                                 completionHandler(true);
                                                                             }];
    
    deleteAction.backgroundColor = SNCOLORBLACK;
    UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
    actions.performsFirstActionWithFullSwipe = NO;
    
    return actions;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

